import { defineComponent, reactive, onMounted, onUnmounted, watch, getCurrentInstance } from 'vue'
import Draw from './draw'
import axios from 'axios'

export default defineComponent({
  components: {
    Draw
  },
  setup() {
    const instance = getCurrentInstance()
    const cdata = reactive({
      category: [], // 用于存储科室名称（deptName）
      lineData: [], // 可根据需求存储number或其他数据
      barData: [],  // 可根据需求存储number或其他数据
      rateData: []
    })
    let intervalId: number | null = null

    // 获取路由参数中的secondColumnValues
    const getSecondColumnValues = () => {
      return instance?.proxy?.$route.query.secondColumnValues as string || ''
    }

    // 定义请求数据的函数（适配新的JSON结构）
    const fetchData = async () => {
      try {
        const params = {
          IIIDataType: getSecondColumnValues(),
          flag: 1
        }
        const response = await axios.get(
          window.globalConfig.baseApi +'/api/Nurse/GetAllStatisticsDataGroupJson',
          { params }
        )
        
        // 假设接口返回的数据结构为 [{deptName: 'xxx', number: xxx}, ...]
        const apiData = response.data || []
        
        // 解析数据并映射到图表所需格式
        cdata.category = apiData.map((item: any) => item.deptName) // 提取科室名称
        cdata.lineData = apiData.map((item: any) => item.number)    // 提取数量到lineData
        cdata.barData = apiData.map((item: any) => item.number)     // 也可根据需求设置为其他值
        
        setData()
      } catch (error) {
        console.error('柱形图数据请求失败:', error)
      }
    };

    const setData = () => {
      cdata.rateData = []
      for (let i = 0; i < Math.min(cdata.barData.length, cdata.lineData.length); i++) {
        if (cdata.lineData[i] !== 0) {
          const rate = cdata.barData[i] / cdata.lineData[i]
          cdata.rateData.push(rate.toFixed(2))
        } else {
          cdata.rateData.push('0.00')
        }
      }
    }

    // 监听路由参数变化重新请求数据
    watch(
      () => getSecondColumnValues(),
      () => {
        fetchData()
      }
    )

    const startTimer = () => {
      fetchData()
      intervalId = window.setInterval(fetchData, 300 * 1000)
    };

    const stopTimer = () => {
      if (intervalId !== null) {
        clearInterval(intervalId)
        intervalId = null
      }
    };

    onMounted(() => {
      startTimer()
    })

    onUnmounted(() => {
      stopTimer()
    });

    return () => {
      return <div>
        <Draw cdata={cdata} />
      </div>
    }
  }
})